//
//  OauthViewController.swift
//  TakeTime
//
//  Created by bachelor on 16/11/1.
//  Copyright © 2016年 bachelor. All rights reserved.
//

import UIKit
import SVProgressHUD
import Alamofire

class OauthViewController: UIViewController, UIWebViewDelegate {
    
    private let WB_Client_ID = "3395405699"
    private let WB_Client_Secret = "5ae984852eb2a0c4da79865a12da49ff"
    private let WB_Redirect_URI = "https://baidu.com"
    
    override func loadView() {
        view = webView
        title = "微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OauthViewController.close))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        webView.delegate = self
        
        loadAuthPage()
        
    }
    
    /// 加载用户登录授权界面
    func loadAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=3395405699&redirect_uri=https://baidu.com"
        let url = URL(string: urlString)
        let request = URLRequest(url: url!)
        
        webView.loadRequest(request)
    }
    
    func loadAccessToken(code:String) {
        let params = ["client_id": WB_Client_ID,
                      "client_secret": WB_Client_Secret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": WB_Redirect_URI]
        
        Alamofire.request("https://api.weibo.com/oauth2/access_token", method: .post, parameters: params).responseJSON { (response) in
            switch response.result {
            case .success(_):
                let JSON = response.result.value
                // 字典转模型
                let account = UserAccount.init(dict: JSON as! [String : AnyObject])
                account.loadUserInfo(finished: { (account, error) in
                    if account != nil {
                        // 1.设置全局的account
                        sharedUserAccount = account
                        // 2.发送通知，切换控制器
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZSwitchVCNotification), object: true)
                        // 3.关闭当前控制器
                        self.close()
                        return
                    }
                    SVProgressHUD.showInfo(withStatus: "加载用户信息失败")
                })
                
            case .failure(let error):
                print(error)
                SVProgressHUD.showInfo(withStatus: "加载token失败")
            }
        }
        
        
    }
    
    func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
        
    }
    // MARK: ----webView代理方法----
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.url!.absoluteString
        
        // 判断是否已回调地址起始
        if !urlString.hasPrefix(WB_Redirect_URI) {
            return true
        }
        let codeStr = "code="
        let queryStr = request.url!.query!
        if queryStr.hasPrefix(codeStr) {
            // code
            let code = queryStr.substring(from: codeStr.endIndex)
            
            loadAccessToken(code: code)
            
        }
        else {
            close()
        }
        
        return false
        
        
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    
    /// 懒加载界面属性
    lazy var webView: UIWebView = {
        return UIWebView()
    }()
    
    override var prefersStatusBarHidden: Bool {
        return true
    }


}
